<!DOCTYPE html>
<html>
<head>
    <title>DOTA2 战况统计</title>
    <style>
        :root {
            --red: #c53d3d;
            --blue: #3d6bc5;
            --dark: #1a1a1a;
        }
        body {
            background: var(--dark);
            color: white;
            font-family: 'Arial', sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        h1, h2 {
            text-align: center;
            font-family: 'Arial Black', sans-serif;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
        }
        #playerPool {
            min-height: 120px;
            margin: 20px 0;
            padding: 10px;
            border: 2px dashed #666;
            border-radius: 8px;
        }
        .container {
            display: flex;
            gap: 20px;
            margin: 20px 0;
        }
        .team-box {
            flex: 1;
            min-height: 400px;
            border: 3px solid;
            padding: 10px;
            border-radius: 10px;
            position: relative;
        }
        #radiant {
            border-color: var(--red);
            background: linear-gradient(to bottom right, rgba(197,61,61,0.1), transparent);
        }
        #dire {
            border-color: var(--blue);
            background: linear-gradient(to bottom right, rgba(61,107,197,0.1), transparent);
        }
        .player {
            display: inline-block;
            padding: 10px;
            margin: 5px;
            border: 2px solid #666;
            border-radius: 5px;
            background: #333;
            cursor: move;
            transition: transform 0.2s;
            position: relative;
        }
        .player:hover {
            transform: scale(1.05);
            box-shadow: 0 0 8px rgba(255,255,255,0.2);
        }
        .controls {
            text-align: center;
            margin: 20px 0;
        }
        button {
            padding: 10px 20px;
            margin: 0 10px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
            transition: all 0.3s;
        }
        button:hover {
            opacity: 0.8;
        }
        #radiantBtn {
            background: var(--red);
            color: white;
        }
        #direBtn {
            background: var(--blue);
            color: white;
        }
        .stats-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .stats-table th, .stats-table td {
            padding: 10px;
            border: 1px solid #444;
            text-align: center;
            cursor: pointer;
        }
        .stats-table th {
            background: #2c2c2c;
        }
        .sortable:hover {
            background: #3a3a3a;
        }
        .player-name {
            cursor: text;
            border-bottom: 1px solid #666;
            margin-bottom: 5px;
            min-width: 80px;
            text-align: center;
        }
        .power-control {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
            margin-top: 5px;
        }
        .delete-btn {
            position: absolute;
            top: -8px;
            right: -8px;
            background: #ff4444;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            display: none;
            cursor: pointer;
        }
        .player:hover .delete-btn {
            display: block;
        }
    </style>
    <script src="//cdn.jsdelivr.net/npm/leancloud-storage@4.12.0/dist/av-min.js"></script>
</head>
<body>
    <h1>是谁在犯罪？谁的打法不团队？</h1>
    
    <div id="playerPool"></div>

    <div class="controls">
        <input type="text" id="playerName" placeholder="输入选手ID">
        <button onclick="addPlayer()">添加选手</button>
    </div>

    <div class="container">
        <div class="team-box" id="radiant" ondrop="drop(event)" ondragover="allowDrop(event)">
            <h2>天辉军团</h2>
            <div id="radiantTotal">总战力：0</div>
        </div>
        <div class="team-box" id="dire" ondrop="drop(event)" ondragover="allowDrop(event)">
            <h2>夜魇军团</h2>
            <div id="direTotal">总战力：0</div>
        </div>
    </div>

    <div class="controls">
        <button id="radiantBtn" onclick="recordResult('radiant')">天辉拿下！</button>
        <button id="direBtn" onclick="recordResult('dire')">夜魇拿下！</button>
        <button onclick="resetPositions()">重置位置</button>
    </div>

    <h2>潮水退去，究竟是谁在裸泳？</h2>
    <table class="stats-table">
        <thead>
            <tr>
                <th onclick="sortStats('name')">选手</th>
                <th onclick="sortStats('wins')">胜场 ↑↓</th>
                <th onclick="sortStats('losses')">败场 ↑↓</th>
                <th onclick="sortStats('rate')">胜率 ↑↓</th>
                <th onclick="sortStats('power')">战力 ↑↓</th>
            </tr>
        </thead>
        <tbody id="statsBody">
        </tbody>
    </table>

<script>
// LeanCloud 初始化（需替换为你的凭证）
AV.init({
    appId: 0gmha9i0rHn16GL5e2wIJQHK-MdYXbMMI,
    appKey: sBa1dtO7EzRmF0OUAp0muKoY,
    serverURL: https://0gmha9i0.api.lncldglobal.com
});

const Player = AV.Object.extend('Player');
let players = [];
let currentSort = { field: null, asc: true };

async function loadPlayers() {
    const query = new AV.Query('Player');
    const results = await query.find();
    players = results.map(p => ({
        id: p.id,
        name: p.get('name'),
        power: p.get('power'),
        wins: p.get('wins'),
        losses: p.get('losses'),
        element: null
    }));
    players.forEach(p => renderPlayer(p));
    updateStats();
}

function createPlayerElement(player) {
    const div = document.createElement('div');
    div.className = 'player';
    div.draggable = true;
    div.innerHTML = `
        <div class="delete-btn" onclick="removePlayer('${player.id}')">×</div>
        <div class="player-name" onclick="editName(this)">${player.name}</div>
        <div class="power-control">
            <button onclick="adjustPower('${player.id}', -100)">-</button>
            <span>${player.power}</span>
            <button onclick="adjustPower('${player.id}', 100)">+</button>
        </div>
    `;
    div.dataset.id = player.id;
    div.addEventListener('dragstart', dragStart);
    return div;
}

async function addPlayer() {
    const nameInput = document.getElementById('playerName');
    const name = nameInput.value.trim();
    if (!name) {
        alert('请输入选手名称');
        return;
    }
    if (players.some(p => p.name === name)) {
        alert('该选手已存在');
        return;
    }
    
    const player = new Player();
    player.set('name', name);
    player.set('power', 1000);
    player.set('wins', 0);
    player.set('losses', 0);
    const savedPlayer = await player.save();
    
    players.push({
        id: savedPlayer.id,
        name,
        power: 1000,
        wins: 0,
        losses: 0,
        element: null
    });
    renderPlayer(players[players.length-1]);
    nameInput.value = '';
    updateStats();
}

async function removePlayer(id) {
    const playerObj = AV.Object.createWithoutData('Player', id);
    await playerObj.destroy();
    
    const index = players.findIndex(p => p.id === id);
    if (index === -1) return;
    players[index].element.remove();
    players.splice(index, 1);
    updateTeamPower();
    updateStats();
}

function dragStart(e) {
    e.dataTransfer.setData('text', e.target.dataset.id);
}

function allowDrop(e) {
    e.preventDefault();
}

function drop(e) {
    e.preventDefault();
    const id = e.dataTransfer.getData('text');
    const playerDiv = document.querySelector(`[data-id="${id}"]`);
    const target = e.target.closest('.team-box');
    
    if (target && !target.contains(playerDiv)) {
        target.appendChild(playerDiv);
        updateTeamPower();
    }
}

function updateTeamPower() {
    const calculatePower = (team) => 
        [...team.querySelectorAll('.player span')]
            .reduce((sum, span) => sum + parseInt(span.textContent), 0);
    
    document.getElementById('radiantTotal').textContent = `总战力：${calculatePower(radiant)}`;
    document.getElementById('direTotal').textContent = `总战力：${calculatePower(dire)}`;
}

async function adjustPower(id, amount) {
    const player = players.find(p => p.id === id);
    player.power = Math.max(0, player.power + amount);
    
    const playerObj = AV.Object.createWithoutData('Player', id);
    playerObj.set('power', player.power);
    await playerObj.save();

    player.element.querySelector('span').textContent = player.power;
    updateTeamPower();
    updateStats();
}

function editName(element) {
    const newName = prompt('输入新名字：', element.textContent);
    if (newName) {
        element.textContent = newName;
        const player = players.find(p => p.element.contains(element));
        player.name = newName;
        const playerObj = AV.Object.createWithoutData('Player', player.id);
        playerObj.set('name', newName);
        playerObj.save();
        updateStats();
    }
}

async function recordResult(winner) {
    const radiantPlayers = radiant.querySelectorAll('.player').length;
    const direPlayers = dire.querySelectorAll('.player').length;
    
    if (radiantPlayers !== 5 || direPlayers !== 5) {
        alert('需要各5名选手！');
        return;
    }
    
    const updates = players.map(async p => {
        const parent = p.element.parentElement;
        if (!parent) return;
        
        const inWinner = parent.id === winner;
        p[inWinner ? 'wins' : 'losses']++;
        p.power += inWinner ? 100 : -100;

        const playerObj = AV.Object.createWithoutData('Player', p.id);
        playerObj.set('wins', p.wins);
        playerObj.set('losses', p.losses);
        playerObj.set('power', p.power);
        await playerObj.save();
        
        p.element.querySelector('span').textContent = p.power;
    });

    await Promise.all(updates);
    updateStats();
    updateTeamPower();
}

function resetPositions() {
    const pool = document.getElementById('playerPool');
    players.forEach(p => {
        if (!pool.contains(p.element)) {
            pool.appendChild(p.element);
        }
    });
    updateTeamPower();
}

function sortStats(field) {
    currentSort.asc = field === currentSort.field ? !currentSort.asc : true;
    currentSort.field = field;
    
    players.sort((a, b) => {
        const valA = field === 'rate' ? a.wins/(a.wins+a.losses) : a[field];
        const valB = field === 'rate' ? b.wins/(b.wins+b.losses) : b[field];
        return currentSort.asc ? valB - valA : valA - valB;
    });
    
    updateStats();
}

function updateStats() {
    const tbody = document.getElementById('statsBody');
    tbody.innerHTML = players.map(p => `
        <tr>
            <td>${p.name}</td>
            <td>${p.wins}</td>
            <td>${p.losses}</td>
            <td>${((p.wins/(p.wins+p.losses)) * 100 || 0).toFixed(1)}%</td>
            <td>${p.power}</td>
        </tr>
    `).join('');
}

// 初始化加载数据
document.addEventListener('DOMContentLoaded', () => {
    loadPlayers();
    document.getElementById('playerName').addEventListener('keypress', (e) => {
        if (e.key === 'Enter') addPlayer();
    });
});
</script>
</body>
</html>